package com.doumi.biz.qadev.api.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;

/**
 * 签名
 */
public class Sign {
	public static String signOuterRequest(Map<String, Object> params, String secret) throws Exception {
		String[] keys = params.keySet().toArray(new String[0]);
		Arrays.sort(keys);
		StringBuilder query = new StringBuilder();
		query.append(secret);
		for (String key : keys) {
			String value = params.get(key) == null ? null : params.get(key).toString();
			if (!org.apache.commons.lang3.StringUtils.isEmpty(key) && !org.apache.commons.lang3.StringUtils.isEmpty(value) && !(params.get(key) instanceof JSONArray) && !(params.get(key) instanceof JSONObject)) {
				query.append(key).append(value);
			}
		}
		query.append(secret);
		byte[] bytes;
		bytes = encryptMD5(query.toString());
		return byte2hex(bytes);
	}

	private static byte[] encryptMD5(String data) throws Exception {
		MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		messageDigest.update(data.getBytes("utf-8"));
		return messageDigest.digest();
	}

	private static String byte2hex(byte[] bytes) {
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex.toUpperCase());
		}
		return sign.toString();
	}
}
